<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/2
 * Time: 16:42
 */
namespace common\models;

use Yii;
use yii\db\ActiveRecord;

class GoodsCateRelation extends ActiveRecord{

	const USE_FLG_YES	= 1;		//启用
	const USE_FLG_NO	= 0;		//禁用

	public static function tableName(){
        return '{{%goods_cate_relation}}';
    }

    //根据category_id获取品类列表
    public function getRelationListByCateId($category_id){
        $where = ['t.use_flg'=>1,'r.category_id'=>$category_id];
        $result = $this::find()->where($where)->alias('r')->select('r.*')->leftJoin('j_goods_tag as t','r.tag_id = t.id')->orderBy('t.sort asc')->asArray()->all();
        $list = array();
        foreach($result as $value){
            $list[$value['category_id']][] = $value;
        }

        return $list;
    }

    public function getTagList(){
        $where = ['t.use_flg'=>1];
        $result = $this::find()->where($where)->alias('r')->select('r.id,t.tag_name,t.tag_alias,r.category_id,r.tag_id')->
                leftJoin('j_goods_tag as t','r.tag_id = t.id')->orderBy('t.sort asc')->asArray()->all();
        $list = array();
        foreach($result as $value){
            $list[$value['category_id']][] = $value;
        }
        return $list;
    }

	/**
	 * @param $category_id根据分类id获取对应的品类信息
	 * @return array|\yii\db\ActiveRecord[]
	 */
	public function getRelationListByCateIdNews($category_id){

		return self::find()->where([
				self::tableName().'.use_flg'		=>self::USE_FLG_YES,
				self::tableName().'.category_id'	=>$category_id,
			])
			->joinWith('goodsCateRelation')
			->asArray()
			->orderBy([GoodsTag::tableName().'.sort'=>SORT_ASC])
			->all();
	}

	/**
	 * @param 关联表j_goods_tag
	 * @return \yii\db\ActiveQuery
	 */
	public function getGoodsCateRelation()
	{
		// hasOne要求返回两个参数 第一个参数是关联表的类名 第二个参数是两张表的关联关系
		return $this->hasOne(GoodsTag::className(), ['id' => 'tag_id']);
	}
}